package com.express;

import com.express.common.SysParamterUtil;
import com.express.interceptor.LoginHandlerInterceptor;
import com.express.service.TokenService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.util.unit.DataSize;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.MultipartConfigElement;

// 加上此注解以便启用XDOC在线HTML文档
//@EnableXDoc
@SpringBootApplication
@MapperScan({"com.express.core.mapper","com.express.sys.mapper"})
public class ExpressApplication implements WebMvcConfigurer {

    @Autowired
    TokenService tokenService;

    @Autowired
    SysParamterUtil paramterUtil;

    public static void main(String[] args) {
        SpringApplication.run(ExpressApplication.class, args);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins(new String[]{"*"})
                .allowCredentials(true)
                .allowedMethods(new String[]{"GET", "POST", "DELETE", "PUT"})
                .maxAge(3600L);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 跨域拦截器需放在最上面
        //registry.addInterceptor(new CorsInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(new LoginHandlerInterceptor(this.tokenService)).excludePathPatterns(new String[] { "/views/**", "/v1/**" });
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize(DataSize.parse("10240KB"));
        factory.setMaxRequestSize(DataSize.parse("102400KB"));
        // 加载系统参数
        paramterUtil.loadParamter();
        return factory.createMultipartConfig();
    }

}
